package com.itheima.reggie.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.itheima.reggie.common.BaseContext;
import com.itheima.reggie.common.R;
import com.itheima.reggie.dto.OrdersDto;
import com.itheima.reggie.entity.*;
import com.itheima.reggie.mapper.OrderMapper;
import com.itheima.reggie.service.*;
import jdk.nashorn.internal.ir.CallNode;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;


@Service
@Slf4j
public class OrderServiceImpl extends ServiceImpl<OrderMapper, Orders> implements OrderService {

    @Autowired
    private ShoppingCartService shoppingCartService;
    @Autowired
    private AddressBookService addressBookService;
    @Autowired
    private UserService userService;
    @Autowired
    private OrderDetailService orderDetailService;
    @Autowired
    private OrderService orderService;

    @Override
    public void submit(Orders orders) {
        Long currentId = BaseContext.getCurrentId();
        //根据当前用户id 查询当前用户购物车
        LambdaQueryWrapper<ShoppingCart> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(ShoppingCart::getUserId,currentId);
        List<ShoppingCart> shoppingCartList = shoppingCartService.list(queryWrapper);

        //根据登录的用户id  查用户数据
        User user = userService.getById(currentId);

        //根据地址id 查地址
        AddressBook addressBook = addressBookService.getById(orders.getAddressBookId());

        //组装订单数据
        long orderId = IdWorker.getId();
        BigDecimal totalAmount = new BigDecimal("0");

        ArrayList<OrderDetail> orderDetailList = new ArrayList<>();
        for (ShoppingCart cart : shoppingCartList) {
            OrderDetail orderDetail = new OrderDetail();
            orderDetail.setName(cart.getName());
            orderDetail.setNumber(cart.getNumber());
            orderDetail.setImage(cart.getImage());
            orderDetail.setDishId(cart.getDishId());
            orderDetail.setSetmealId(cart.getSetmealId());
            orderDetail.setDishFlavor(cart.getDishFlavor());
            orderDetail.setAmount(cart.getAmount());
            orderDetail.setOrderId(orderId);

            //计算金额
            //totalAmount += amout * number
            totalAmount = totalAmount.add(cart.getAmount().multiply(new BigDecimal(cart.getNumber())));
            orderDetailList.add(orderDetail);
        }

        //3. 组装订单的数据
        orders.setId(orderId);//订单表主键ID
        orders.setNumber(String.valueOf(orderId));//订单号
        orders.setUserId(BaseContext.getCurrentId());//当前用户ID
        orders.setAddress(addressBook.getDetail());//收件地址
        orders.setConsignee(addressBook.getConsignee());//收件人
        orders.setPhone(addressBook.getPhone());//收件人手机号
        orders.setStatus(2);//待派送
        orders.setOrderTime(LocalDateTime.now());
        orders.setCheckoutTime(LocalDateTime.now());
        orders.setUserName(user.getName());
        orders.setAmount(totalAmount);//总金额

        //保存订单
        this.save(orders);
        orderDetailService.saveBatch(orderDetailList);

        //删除购物车
        shoppingCartService.remove(queryWrapper);
    }

    @Override
    public  Page<OrdersDto> userPage(Integer page, Integer pageSize ) {
        Page<Orders> ordersPage = new Page<>(page,pageSize);


        Long currentId = BaseContext.getCurrentId();

        LambdaQueryWrapper<Orders> ordersLambdaQueryWrapper = new LambdaQueryWrapper<>();
        ordersLambdaQueryWrapper.eq(Orders::getUserId,currentId);
        ordersLambdaQueryWrapper.orderByDesc(Orders::getOrderTime);
        Page<Orders> ordersPage1 = orderService.page(ordersPage, ordersLambdaQueryWrapper);

        List<Orders> records = ordersPage1.getRecords();

        Page<OrdersDto> ordersDtoPage = new Page<>();
        ordersDtoPage.setTotal(ordersPage.getTotal());
        List<OrdersDto> collect = records.stream().map(record -> {
            OrdersDto ordersDto = new OrdersDto();
            BeanUtils.copyProperties(record, ordersDto);

            LambdaQueryWrapper<OrderDetail> orderDetailLambdaQueryWrapper = new LambdaQueryWrapper<>();
            orderDetailLambdaQueryWrapper.eq(OrderDetail::getOrderId, record.getId());
            List<OrderDetail> list = orderDetailService.list(orderDetailLambdaQueryWrapper);

            if (list != null) {
                ordersDto.setOrderDetails(list);

            }
            return ordersDto;

        }).collect(Collectors.toList());
        ordersDtoPage.setRecords(collect);
        return ordersDtoPage;

    }
}